package Util

import (
	"strings"
	"unicode/utf8"
)

// SafeSubstring 安全地截取 strings.Builder 中的字符串内容，返回新的 strings.Builder
func SafeSubstring(builder *strings.Builder, maxRunes int) *strings.Builder {
	s := builder.String()
	length := utf8.RuneCountInString(s)

	if length == 0 || maxRunes <= 0 {
		return &strings.Builder{}
	}

	end := length
	if end > maxRunes {
		end = maxRunes
	}

	var resultBuilder strings.Builder
	// 预先分配足够的容量，避免多次扩容
	resultBuilder.Grow(len(s))

	count := 0
	for i := 0; i < len(s); {
		r, size := utf8.DecodeRuneInString(s[i:])
		if count >= end {
			break
		}
		resultBuilder.WriteRune(r)
		i += size
		count++
	}

	return &resultBuilder
}
